package limousine.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Hashtable;
import java.util.logging.Level;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

// log4j
import limousine.dbservice.UsersService;
import limousine.util.Func;
import limousine.util.Service;
//import org.apache.log4j.Logger;

/**
 * Servlet implementation class for Servlet: TestDB
 *
 */
public class CheckUsername extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

   // static Logger logger = Logger.getLogger(CheckUsername.class.getName());
    /* (non-Java-doc)
     * @see javax.servlet.http.HttpServlet#HttpServlet()
     */

    /* (non-Java-doc)
     * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doPost(request, response);
    }

    /* (non-Java-doc)
     * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        System.out.println("--CheckUsername...");

        // Optional: Only supports output of jpg and png, defaults to png if not
        // specified
        String id = getParam(request, "id", "");
        // Optional: Folder in web app where images are located, defaults to


        Service service = new Service();
        service.setServletContext(getServletContext());
        DataSource ds = service.getDataSource();

        UsersService us = new UsersService();
        us.setDataSource(ds);

        boolean exist = us.checkUsernameExist(id);

              

        if (exist) {
            Func func = new Func();
            PrintWriter out = response.getWriter();

            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-type", "text/html; charset=UTF-8");

            StringBuffer sb = new StringBuffer();
            sb.append("NO");

            out.print(sb.toString());
            out.flush();
        }
    }

// Check the param if it's not present return the default
    private String getParam(HttpServletRequest request, String param, String def) {
        String parameter = request.getParameter(param);


        if (parameter == null || "".equals(parameter)) {
            return def;


        } else {
            return parameter;

        }
    }
}
